<template>
  <div class="app-container">
    <h1 class="text-center">记账凭证({{getCurrentYear()}}年{{getCurrentMonth()}}期)</h1>

    <el-form ref="FinRecordVoucherRef"  :inline="true" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="凭证字" prop="recordTag">
            <div id="select-container">
            <el-select v-model="form.recordTag"   size="small" style="width: 80px">
              <el-option  label="收" value="收"/>
              <el-option  label="付" value="付"/>
              <el-option  label="转" value="转"/>
              <el-option  label="记" :value="'记'"/>
            </el-select>
            </div>
          </el-form-item>
        <el-form-item label="号" prop="recordNo" label-width="30px">
          <el-input type="number" v-model="form.recordNo"   style="width: 80px"/>
        </el-form-item>
        <el-form-item label="日期" prop="recordDate">
          <el-date-picker clearable
                          v-model="form.recordDate"
                          type="date"
                          value-format="YYYY-MM-DD HH:mm"
                          placeholder="请选择凭证时间">
          </el-date-picker>
          <FinRecordVoucherStatus style="margin-left: 20px" :status-val="form.status"></FinRecordVoucherStatus>

        </el-form-item>
      </el-form>
    <el-table :data="itemList" border stripe :summary-method="getSummaries" show-summary>
      <el-table-column label="摘要" align="center" >
        <template #default="scope">
          <el-input v-model="scope.row.description" />
        </template>
      </el-table-column>
      <el-table-column label="会计科目" align="center" width="500px" >
        <template #default="scope">
          <el-cascader v-model="scope.row.subjectId" @change="handleChangeSubject(scope.row)" filterable :options="finSubjectTreeSelect"  style="width: 100%;"/>
        </template>
      </el-table-column>
      <el-table-column label="借方" align="center" >
        <template #default="scope">
          <el-input-number v-model="scope.row.jieAmount" :precision="2" controls-position="right" style="width: 90%;">
            <template #prefix>
              <span>￥</span>
            </template>
          </el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="贷方" align="center" >
        <template #default="scope">
          <el-input-number v-model="scope.row.daiAmount" :precision="2" controls-position="right" style="width: 90%;">
            <template #prefix>
              <span>￥</span>
            </template>
          </el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150px">
        <template #default="scope">
          <el-button link type="primary" v-if="form.status=='DRAFT'" icon="Plus" @click="handleAddItem(scope.$index)" v-hasPermi="['project:FinRecordVoucher:edit']"></el-button>
          <el-button link type="primary" v-if="form.status=='DRAFT'"  icon="Delete" @click="handleDeleteItem(scope.$index)" v-hasPermi="['project:FinRecordVoucher:remove']"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="text-center" style="margin-bottom: 20px;padding-top: 20px">
      <el-button style="float: left" v-if="form.id" type="primary" size="small" @click="preInfo()">上一条</el-button>
      <div v-if="form.id" style="display: inline-flex;margin-right: 15px">
        <el-button type="success" v-if="form.status=='DRAFT'"
                    @click="handleCheck(form,true)" v-hasPermi="['project:FinRecordVoucher:check']">
            审核
        </el-button>

        <el-button type="success" v-if="form.status=='CHECKED'"
                    @click="handleRecordToBook(form)" v-hasPermi="['project:FinRecordVoucher:recordToBook']">
            记账
        </el-button>
        <el-button type="danger" v-if="form.status=='CHECKED'"
                   @click="handleCheck(form,false)" v-hasPermi="['project:FinRecordVoucher:checkCancel']">
          反审核
        </el-button>
        <el-button type="danger" v-if="form.status=='RECORDED'"
                    @click="handleRecordCancelToBook(form)" v-hasPermi="['project:FinRecordVoucher:recordToBookCancel']">
           反记账
        </el-button>
      </div>
      <el-button type="primary" v-if="form.id==null || form.status=='DRAFT'" @click="submitForm(false)">保 存</el-button>
      <el-button type="primary" v-if="form.id==null || form.status=='DRAFT'" @click="submitForm(true)">保 存 & 新 增</el-button>
      <el-button v-if="form.id || form.status!='DRAFT'" type="primary"
          plain icon="Plus" @click="handleAdd" v-hasPermi="['project:FinRecordVoucher:add']">新增</el-button>
      <el-button  type="primary"  v-if="form.id"
                 plain icon="RefreshRight" @click="init()" v-hasPermi="['project:FinRecordVoucher:add']">刷新</el-button>
      <el-button type="danger" v-if="form.id && form.status=='DRAFT'" plain icon="Delete" @click="handleDelete"
                 v-hasPermi="['project:FinRecordVoucher:remove']"
      >删除</el-button>
      <el-button style="float: right" type="primary" v-if="form.id"  size="small" @click="nextInfo()">下一条</el-button>

    </div>
  </div>
</template>

<script setup name="FinRecordVoucher">
import {
  addFinRecordVoucher, cancelRecordFinRecordVoucher, checkFinRecordVoucher, delFinRecordVoucher, getFinRecordVoucher,
  getMaxRecordNoFinRecordVoucher, nextFinRecordVoucher, preFinRecordVoucher, recordFinRecordVoucher,
  updateFinRecordVoucher
} from "@/api/project/FinRecordVoucher";
import {getCurrentMonth, getCurrentYear} from "../../../utils/auth.js";
import {listFinSubjectTreeSelect} from "@/api/project/FinSubject.js";
import {formatDate} from "@vueuse/core";
import {deepClone} from "@/utils/index.js";
import {useRouter} from "vue-router";
import FinRecordVoucherStatus from "@/components/enumShow/FinRecordVoucherStatus.vue";

const { proxy } = getCurrentInstance();

const channelUpdateList = new BroadcastChannel("updateFinRecordVoucherList");

const data = reactive({
  form: {},
  itemList:[],
  finSubjectTreeSelect:[],
  minRecordNo:0,
  rules: {
    recordDate: [
      { required: true, message: "凭证时间不能为空", trigger: "blur" }
    ],
    recordNo: [
      { required: true, message: "凭证号不能为空", trigger: "blur" }
    ],
    yearValue: [
      { required: true, message: "年份不能为空", trigger: "blur" }
    ],
    monthValue: [
      { required: true, message: "月份不能为空", trigger: "blur" }
    ],
    yearAndMonth: [
      { required: true, message: "年份和月份不能为空", trigger: "blur" }
    ]
  }
});

const { form, rules,itemList,finSubjectTreeSelect,minRecordNo } = toRefs(data);
const router = useRouter()

watch(
    () => router.currentRoute.value.name,
    (newRouterName) => {
      console.log('newRouterName',newRouterName)
      if(newRouterName==='FinRecordVoucherCreate'){
        console.log("FinRecordVoucherCreate--->init()")
        init();
      }
    },
    { immediate: true }
)

function refreshData(id){
  getFinRecordVoucher(id).then(response => {
    form.value = response.data;
    itemList.value = response.data.itemList;
  });
}

function init(){
  getFinSubjectTreeSelect();
  if (proxy.$route.query.id != undefined) {
    getFinRecordVoucher(proxy.$route.query.id).then(response => {
      form.value = response.data;
      itemList.value = response.data.itemList;
      if(itemList.value.length<8){
        for(let i=itemList.value.length;i<8;i++){
          itemList.value.push({
            recordSeq:i+1
          })
        }
      }
    });
  }else{
    reset();
  }
}

function handleAdd() {
  reset();
}
function nextInfo(){
  if(form.value.id){
    nextFinRecordVoucher(form.value).then(response => {
      gotoEdit(response.data);
    });
  }else{
    proxy.$modal.msgError("找不到凭证id！");
  }
}

function gotoEdit(formData){
  if(formData){
    form.value = formData;
    itemList.value = formData.itemList;
    if(itemList.value.length<8){
      for(let i=itemList.value.length;i<8;i++){
        itemList.value.push({
          recordSeq:i+1
        })
      }
    }
  }else{
    proxy.$modal.msgError("已经没有数据了！");
  }
}
function preInfo(){
  if(form.value.id){
    preFinRecordVoucher(form.value).then(response => {
      gotoEdit(response.data);
    });
  }else{
    proxy.$modal.msgError("找不到凭证id！");
  }
}
function handleCheck(row,res) {
  checkFinRecordVoucher(row.id,res).then(response => {
    proxy.$modal.msgSuccess("修改成功");
    channelUpdateList.postMessage({ message: "updateList" });
    refreshData(row.id);
  });
}

function handleRecordToBook(row) {
  recordFinRecordVoucher(row.id).then(response => {
    proxy.$modal.msgSuccess("记账成功");
    channelUpdateList.postMessage({ message: "updateList" });
    refreshData(row.id);
  });
}

function handleRecordCancelToBook(row) {
  cancelRecordFinRecordVoucher(row.id).then(response => {
    proxy.$modal.msgSuccess("反记账成功");
    channelUpdateList.postMessage({ message: "updateList" });
    refreshData(row.id);
  });
}

function handleChangeSubject(row){
  console.log(row.subjectId)
}

function getFinSubjectTreeSelect(){
  listFinSubjectTreeSelect().then(response => {
    finSubjectTreeSelect.value = response.data;
  });
}

function getSummaries(param){
  let sums = [];
  sums[0] = h('div', { style: { textDecoration: 'underline' } }, [
    '合计',])
  sums[1] = '';
  sums[2] = 0;
  sums[3] = 0;
  const { columns, data } = param
  data.forEach(d=>{
    if(d.jieAmount != undefined){
      sums[2] =sums[2] + d.jieAmount;
    }
    if(d.daiAmount != undefined){
      sums[3] = sums[3] +d.daiAmount;
    }
  });
  console.log("data",data)
  return sums;
}

function handleAddItem(index) {
  itemList.value.splice(index+1, 0, [{}])
  let i=0;
  itemList.value.forEach(item=>{
    item.recordSeq = i+1;
    i++;
  })
}

function handleDeleteItem(index) {
  itemList.value.splice(index, 1)
  let i=0;
  itemList.value.forEach(item=>{
    item.recordSeq = i+1;
    i++;
  })
}

function handleUpdateRecordNo(){
  getMaxRecordNoFinRecordVoucher(form.value.recordTag,getCurrentYear(),getCurrentMonth()).then(response => {
    form.value.recordNo = response.data;
    minRecordNo.value = response.data;
  });
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    recordDate: null,
    recordTag: '记',
    recordNo: null,
    jieAmount: null,
    daiAmount: null,
    yearValue: null,
    monthValue: null,
    yearAndMonth: null,
    status: 'DRAFT',
    packageId: null,
    createId: null,
    createBy: null,
    createTime: null,
    updateId: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  itemList.value = [];
  for(let i=0;i<8;i++){
    itemList.value.push({
      recordSeq:i+1
    })
  }
  proxy.resetForm("FinRecordVoucherRef");
  form.value.recordDate = formatDate(new Date(),'YYYY-MM-DD HH:mm');
  console.log("form.value.recordDate",form.value.recordDate);
  handleUpdateRecordNo();
}
/** 提交按钮 */
function submitForm(toCreate) {
  let jieAmount = 0;
  let daiAmount = 0;
  let itemListNew = []
  console.log("itemList bbbbbb-->",itemList.value)
  itemList.value.forEach(item=>{
    if(item.subjectId == undefined){
      return;
    }
    console.log(item.subjectId)

    let itemNew = deepClone(item);
    if(Array.isArray(item.subjectId)){
      itemNew.subjectId = itemNew.subjectId[itemNew.subjectId.length -1 ];
    }
    console.log("itemNew--->",itemNew)
    if(itemNew.subjectId!=undefined){
      if(itemNew.jieAmount==undefined && itemNew.daiAmount == undefined){
        proxy.$modal.msgError("请填写借方或贷山金额，请检查！");
        return;
      }
      if(itemNew.description==undefined|| itemNew.description.trim() ==''){
        proxy.$modal.msgError("请填写摘要，请检查！");
        return;
      }
    }
    if(itemNew.jieAmount != undefined){
      jieAmount =jieAmount + itemNew.jieAmount;
    }
    if(itemNew.daiAmount != undefined){
      daiAmount = daiAmount +itemNew.daiAmount;
    }
    itemListNew.push(itemNew);
  });
  form.value.jieAmount = jieAmount.toFixed(2);
  form.value.daiAmount = daiAmount.toFixed(2);
  form.value.itemList = itemListNew;
  if(jieAmount.toFixed(2)!=daiAmount.toFixed(2)){
    proxy.$modal.msgError("保存失败，借贷金额 不 相等，请检查！");
    console.log("itemList aaaaa-->",itemList.value)
    console.log("itemListNew aaaaa-->",itemListNew)
    return;
  }
  if(jieAmount == 0){
    proxy.$modal.msgError("请输入凭证项，请检查！");
    return;
  }
  proxy.$refs["FinRecordVoucherRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateFinRecordVoucher(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          channelUpdateList.postMessage({ message: "updateList" });
          if(toCreate!=undefined && toCreate){
            reset();
          }
        });
      } else {
        addFinRecordVoucher(form.value).then(response => {
          channelUpdateList.postMessage({ message: "updateList" });
          proxy.$modal.msgSuccess("新增成功");
          if(toCreate!=undefined && toCreate){
            reset();
          }else{
            console.log("resproxy.$routerponse---->",response)
            proxy.$router.push({
              path: '/finTotal/FinRecordVoucherCreate',
              query: { id: response.data.id }
            });
            init();
          }
        });
      }
    }
  });
}

function handleDelete() {
  const desc = form.value.recordTag + form.value.recordNo;
  proxy.$modal.confirm('是否确认删除记账凭证编号为"' + desc + '"的数据项？').then(function() {
    return delFinRecordVoucher(form.value.id);
  }).then(() => {
    proxy.$modal.msgSuccess("删除成功");
    reset();
    // 通过广播频道发送消息
    channelUpdateList.postMessage({ message: "updateList" });
  }).catch(() => {});
}


init()
</script>
<style scoped>
.el-select__wrapper {
  align-items: center;
  border-radius: 0;
  box-shadow: 0 1px;
  box-sizing: border-box;
  cursor: pointer;
  display: flex;
  font-size: 14px;
  gap: 6px;
  line-height: 24px;
  min-height: 32px;
  padding: 4px 12px;
  position: relative;
  text-align: left;
}
</style>
